package com.fire.web.modules.all.controller;

import com.fire.web.modules.all.constant.ErrorCodeConstants;
import com.fire.web.modules.all.entity.AjaxResult;
import com.fire.web.modules.all.utils.FastDFSClientWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FastDFSController {
	@Autowired
	FastDFSClientWrapper client;

	/**
	 * 图片上传
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult uploadSwitch(MultipartFile file) throws IOException {
		Map<String, String> map = new HashMap<>(2);

		Integer width = null;
		Integer height = null;
		AjaxResult ajaxResult = new AjaxResult();
		try {
			BufferedImage image = ImageIO.read(file.getInputStream());
			if (null == image) {
				return new AjaxResult(ErrorCodeConstants.PATTERN_ERROR, "该文件不是图片格式", "该文件不是图片格式");
			}
			width = image.getWidth();
			height = image.getHeight();
			String fileUrl = client.uploadFile(file);
			ajaxResult = new AjaxResult(ErrorCodeConstants.SUCCESS, "上传成功", fileUrl, "上传成功");
		} catch (IOException e) {
			e.printStackTrace();
			ajaxResult = new AjaxResult(ErrorCodeConstants.UPLOAD_FAIL, "上传失败", "上传失败");
		}
		/*if(width!=null && height!=null) {
			fileUrl.put("width", width.toString());
			fileUrl.put("height", height.toString());
		}*/
		return ajaxResult;
	}


	/**
	 * 删除上传图片
	 *
	 * @param fileUrl
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/deletepic", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult deleteUploadFile(String fileUrl) throws Exception {
		String resultCode = client.deleteFile(fileUrl);
		if ("1".equals(resultCode)) {
			return new AjaxResult(ErrorCodeConstants.DELETE_FAIL, "删除失败", "删除失败");
		}
		return new AjaxResult(ErrorCodeConstants.SUCCESS, "删除成功", "删除成功");
	}

}
